from django.shortcuts import render

# Create your views here.
from .ser import *
from rest_framework.views import APIView
from rest_framework.response import Response

class UserShowView(APIView):
    def get(self,request):
        user = User.objects.all()
        user_ser = UserModelSerializer(user,many=True)
        return Response(user_ser.data)
    def put(self,request):
        user = User.objects.filter(id=request.data.get('id')).first()
        if user.vip == 1:
            user.vip += 1
            Coupon.objects.update(user=1)
            return Response({'msg':'用户已升级','code':'200'})
        else:
            return Response({'msg':'用户已升级','code':'200'})
    def post(self,request):
        name = request.data.get('name')
        user = User.objects.get(name=name)
        return Response({'msg':'登录成功','code':200,'user_id':user.id,'user_name':user.name})
class ProductView(APIView):
    def get(self,request):
        book = Product.objects.all()
        book_ser = ProductModelSerializer(book,many=True)
        return Response(book_ser.data)
class CartAPIView(APIView):
    def post(self,request):
        book = request.data.get('product')
        user = request.data.get('user')
        num = request.data.get('num')
        print(request.data)
        pro = Product.objects.filter(id=book).first()
        print(pro)
        car = Cart.objects.filter(product=book).first()
        print(pro)
        if car:
            car.num += 1
            pro.inventory -= 1
            pro.save()
            print(pro)
            if pro.inventory == 0:
                return Response({'msg':'库存不足','code':200})
            else:
                car.save()
                return Response({'msg':'再次购买成功','code':200})
        cart_ser = CartModelSerializer(data=request.data)
        cart_ser.is_valid()
        cart_ser.save()
        pro.inventory -= 1
        pro.save()
        return Response({'msg':'购买成功','code':200})
    def get(self,request):
        user_id = request.query_params.get('user_id')
        cou_id = request.query_params.get('cou_id')
        cart = Cart.objects.filter(user=user_id)
        cart_ser = CartShowModelSerializer(cart,many=True)
        cou = Coupon.objects.filter(user=user_id)
        cou_ser = CouponModelSerializer(cou,many=True)
        return Response({'cart_list':cart_ser.data,'cou_list':cou_ser.data})



